import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  Spin,
  Tabs,
  Col,
  Row,
  Empty,
  Tree,
  InputNumber,
  Switch,
} from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import workshopService, {
  type PageListReq,
} from "@/api/services/mes/workshopService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import type { MesWorkshop } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import MesWorkshopMachinePage, {
  type MesWorkshopMachineHandles,
} from "./machine";
import MesWorkshopProductPage, {
  type MesWorkshopProductHandles,
} from "./product";
import MesWorkshopUserPage, { type MesWorkshopUserHandles } from "./user";
import { debounce } from "lodash-es";

const { TextArea } = Input;

export default function MesWorkshopPage() {
  const machineRef = useRef<MesWorkshopMachineHandles>(null);
  const productRef = useRef<MesWorkshopProductHandles>(null);
  const userRef = useRef<MesWorkshopUserHandles>(null);

  const [loading, setLoading] = useState(false);
  const [treeLoading, setTreeLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    type: undefined,
    code: undefined,
    name: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<MesWorkshop[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [tableSize, setTableSize] = useState<"large" | "middle" | "small">(
    "middle"
  );
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<MesWorkshop | null>(null);
  const [form] = Form.useForm();
  // 监听 type 字段
  const selectedType = Form.useWatch("type", form);

  const [isView, setIsView] = useState(true);

  const [treeList, setTreeList] = useState<MesWorkshop[]>([]);
  const [selectWorkshop, setSelectWorkshop] = useState<MesWorkshop | null>(
    null
  );
  const [searchValue, setSearchValue] = useState("");

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 403;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const typeOptions = useDictionary("workshop_type");
  const enableFlagOptions = useDictionary("system_true_false");

  const columns: ColumnsType<MesWorkshop> = [
    {
      title: "类型",
      width: 120,
      key: "type",
      dataIndex: "type",
      render: (_, record) => (
        <TableDictTag dictCode="workshop_type" value={record.type ?? ""} />
      ),
    },
    {
      title: "编码",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "名称",
      width: 120,
      key: "name",
      dataIndex: "name",
    },
    {
      title: "是否启用",
      width: 120,
      key: "enableFlag",
      dataIndex: "enableFlag",
      render: (_, record) => (
        <TableDictTag
          dictCode="system_true_false"
          value={record.enableFlag ?? ""}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  const [selectedValues, setSelectedValues] = useState<string[]>(() =>
    columns
      .filter((col) => col.key !== "operation")
      .map((col) => (col.key ? String(col.key) : ""))
  );

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  const filteredColumns = useMemo(() => {
    return [
      ...columns.filter(
        (col) =>
          selectedValues.includes(String(col.key)) || col.key === "operation"
      ),
    ].sort((a, b) => {
      const originalIndex = columns.findIndex((c) => c.key === a.key);
      const targetIndex = columns.findIndex((c) => c.key === b.key);
      return originalIndex - targetIndex;
    });
  }, [selectedValues]);

  //加载树形结构数据
  const fetchTreeList = async () => {
    setTreeLoading(true);
    await workshopService
      .treeList(queryParams)
      .then((data) => {
        if (data) {
          setTreeList(data);
        }
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setTreeLoading(false);
      });
  };

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    workshopService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchTreeList();
  }, []);

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (mesWorkshop: MesWorkshop) => {
    setEditingData(mesWorkshop);
    form.setFieldsValue(mesWorkshop);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (mesWorkshop: MesWorkshop) => {
    setEditingData(mesWorkshop);
    form.setFieldsValue(mesWorkshop);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: MesWorkshop) => {
    try {
      setSubmitLoading(true);

      //车间建模设备信息
      const deleteMachineIds = machineRef.current?.getDeleteIds();
      const addMachines = machineRef.current?.getAddList();
      const updateMachines = machineRef.current?.getUpdateList();

      //关联产品
      const deleteProductIds = productRef.current?.getDeleteIds();
      const addProducts = productRef.current?.getAddList();
      const updateProducts = productRef.current?.getUpdateList();

      //车间员工
      const deleteUserIds = userRef.current?.getDeleteIds();
      const addUsers = userRef.current?.getAddList();
      const updateUsers = userRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteMachineIds: deleteMachineIds,
        addMachines: addMachines,
        updateMachines: updateMachines,
        deleteProductIds: deleteProductIds,
        addProducts: addProducts,
        updateProducts: updateProducts,
        deleteUserIds: deleteUserIds,
        addUsers: addUsers,
        updateUsers: updateUsers,
      };
      if (editingData) {
        await workshopService.update(data);
        toast.success("更新车间 成功");
      } else {
        await workshopService.add(data);
        toast.success("创建车间 成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
      fetchTreeList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  // 添加车间按钮
  const handleAddWorkshop = () => {
    setEditingData(null);
    form.resetFields();
    form.setFieldValue("parentId", 0);
    form.setFieldValue("type", "WORKSHOP");
    form.setFieldValue("enableFlag", "1");
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    form.setFieldValue("enableFlag", "1");
    form.setFieldValue("parentId", selectWorkshop?.id || 0);
    form.setFieldValue("parentCode", selectWorkshop?.code || "");
    form.setFieldValue("parentName", selectWorkshop?.name || "");
    if (selectWorkshop) {
      if (selectWorkshop.type === "WORKSHOP") {
        form.setFieldValue("type", "LINE");
      } else if (selectWorkshop.type === "LINE") {
        form.setFieldValue("type", "STATION");
      }
    }
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await workshopService.remove(selectedRowKeys);
      toast.success("删除车间 成功");
      setSelectedRowKeys([]);
      fetchPageList();
      fetchTreeList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 过滤树数据（递归搜索）
  const filteredTreeData = useMemo(() => {
    // 无搜索值时返回完整数据
    if (!searchValue) return treeList;

    const loop = (data: MesWorkshop[]): MesWorkshop[] => {
      return data
        .map((item) => {
          const match = item.name
            .toLowerCase()
            .includes(searchValue.toLowerCase());
          const children = item.children ? loop(item.children) : undefined;
          const hasChildMatch = children && children.length > 0;

          return match || hasChildMatch ? { ...item, children } : null;
        })
        .filter(Boolean) as MesWorkshop[];
    };

    return loop(treeList);
  }, [treeList, searchValue]);

  // 递归查找节点数据
  const findNodeById = useCallback(
    (id: string, nodes: MesWorkshop[]): MesWorkshop | undefined => {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = findNodeById(id, node.children);
          if (found) return found;
        }
      }
      return undefined;
    },
    []
  );

  // 处理树节点点击
  const handleNodeSelect = useCallback(
    (selectedKeys: React.Key[]) => {
      if (selectedKeys.length === 0) {
        setSelectWorkshop(null);
        return;
      }

      const selectedId = selectedKeys[0] as string;
      const foundNode = findNodeById(selectedId, treeList);

      if (foundNode) {
        setSelectWorkshop(foundNode);
        setQueryParams((prev) => ({
          ...prev,
          parentId: selectedId,
          page: 1,
        }));
      }
    },
    [treeList, findNodeById]
  );

  // 防抖处理搜索输入
  const handleSearch = debounce((value: string) => {
    setSearchValue(value);
  }, 300);

  return (
    <>
      <Row gutter={16} className="h-[calc(100vh-120px)]">
        {/* 左侧树形结构 */}
        <Col span={5} className="h-full">
          <Card
            className="h-full overflow-auto"
            bodyStyle={{ height: "100%", padding: "16px" }}
          >
            <Input.Search
              placeholder="搜索"
              onChange={(e) => handleSearch(e.target.value)}
              allowClear
              className="mb-4"
            />
            {treeLoading ? (
              <Spin spinning tip="加载中..." />
            ) : filteredTreeData.length === 0 ? (
              <Empty description={searchValue ? "无匹配结果" : "暂无数据"} />
            ) : (
              <Tree
                treeData={filteredTreeData}
                fieldNames={{ key: "id", children: "children", title: "name" }}
                onSelect={handleNodeSelect}
              />
            )}
          </Card>
        </Col>
        <Col span={19}>
          <Spin spinning={submitLoading} tip="数据提交中..." size="large">
            <Card className="mb-4">
              <Form
                layout="inline"
                onFinish={(values) => {
                  setQueryParams((prev) => ({
                    ...prev,
                    ...values,
                    page: 1,
                  }));
                }}
              >
                <Form.Item name="type" label="类型">
                  <Select options={typeOptions} placeholder="请输入类型" style={{ width: 170 }} />
                </Form.Item>
                <Form.Item name="code" label="编码">
                  <Input placeholder="请输入编码" allowClear />
                </Form.Item>
                <Form.Item name="name" label="名称">
                  <Input placeholder="请输入名称" allowClear />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button
                    className="ml-2"
                    onClick={() => {
                      setQueryParams({ page: 1, pageSize: 10 });
                    }}
                  >
                    重置
                  </Button>
                </Form.Item>
              </Form>
            </Card>
            <div className="h-4" />
            <Card>
              <div className="flex justify-between mb-4">
                <div className="flex gap-2">
                  <Button type="primary" onClick={handleAddWorkshop}>
                    新增车间
                  </Button>
                  <Button
                    type="primary"
                    onClick={handleAdd}
                    disabled={selectWorkshop?.type !== "LINE"}
                  >
                    新增子区域
                  </Button>
                  <Button
                    danger
                    disabled={selectedRowKeys.length === 0}
                    onClick={handleDelete}
                  >
                    删除
                  </Button>
                </div>
                <TableToolbar
                  onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
                  onSizeChange={setTableSize}
                  columns={columns}
                  selectedValues={selectedValues}
                  onColumnChange={setSelectedValues}
                />
              </div>
              <Table
                rowKey="id"
                size={tableSize}
                scroll={{ x: "max-content", y: tableScrollY }}
                loading={loading}
                pagination={{
                  total,
                  current: queryParams.page,
                  pageSize: queryParams.pageSize,
                  onChange: handlePageChange,
                }}
                columns={filteredColumns}
                dataSource={list}
                rowSelection={{
                  type: "checkbox",
                  selectedRowKeys: selectedRowKeys,
                  onChange: (selectedKeys) => {
                    setSelectedRowKeys(selectedKeys as string[]);
                  },
                }}
              />
            </Card>
          </Spin>
        </Col>
      </Row>
      <Drawer
        title={editingData ? "编辑车间 " : "新增车间 "}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button type="primary" onClick={() => form.submit()}>
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          {selectedType !== "WORKSHOP" && (
            <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="parentId"
                label="上级ID"
                style={{ display: "none" }}
              >
                <Input disabled />
              </Form.Item>
              <Form.Item name="parentCode" label="上级编码">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="parentName" label="上级名称">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          )}
          
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="编码"
                rules={[{ required: true, message: "请填写编码" }]}
              >
                <Input placeholder="请输入编码" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="名称"
                rules={[{ required: true, message: "请填写名称" }]}
              >
                <Input placeholder="请输入名称" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item name="type" label="类型">
                <Select options={typeOptions} disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="ownerId" label="负责人">
                <Input placeholder="请输入负责人" allowClear />
              </Form.Item>
            </Col>
          </Row>
          {selectedType === "LINE" && (
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="capacity" label="日产能">
                  <InputNumber min={1} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="hourCapacity" label="小时产能">
                  <InputNumber min={1} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
            </Row>
          )}
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="enableFlag"
                label="是否启用"
                rules={[
                  {
                    required: true,
                    message: "请填写是否启用",
                  },
                ]}
              >
                <Switch
                  checkedChildren="是"
                  unCheckedChildren="否"
                  checkedValue="1"
                  unCheckedValue="0"
                  disabled={isView}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="remark" label="备注">
                <Input allowClear />
              </Form.Item>
            </Col>
          </Row>
          {selectedType === "LINE" && (
            <Tabs
              defaultActiveKey="1"
              items={[
                {
                  key: "1  ",
                  label: "设备信息 ",
                  children: (
                    <MesWorkshopMachinePage
                      ref={machineRef}
                      parentId={editingData?.id}
                    />
                  ),
                },
                {
                  key: "2  ",
                  label: "生产产品",
                  children: (
                    <MesWorkshopProductPage
                      ref={productRef}
                      parentId={editingData?.id}
                    />
                  ),
                },
                {
                  key: "3  ",
                  label: "员工信息",
                  children: (
                    <MesWorkshopUserPage
                      ref={userRef}
                      parentId={editingData?.id}
                    />
                  ),
                },
              ]}
            />
          )}
        </Form>
      </Drawer>
    </>
  );
}
